#include "ShaderProgram.h"
#include <glad/glad.h>
#include <iostream>
using namespace std;
unsigned int ShaderProgram::createShaderProgram()
{
    if (shaderProgram != 0)
    {
        cout << "hit shaderProgram which is " << shaderProgram << endl;
        return shaderProgram;
    }

    int vertexShader = compileShader(vertexShaderSource, GL_VERTEX_SHADER);

    int fragmentShader =
        compileShader(fragmentShaderSource, GL_FRAGMENT_SHADER);

    shaderProgram = glCreateProgram();

    glAttachShader(shaderProgram, vertexShader);
    glAttachShader(shaderProgram, fragmentShader);
    glLinkProgram(shaderProgram);

    int success;
    glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);

    if (!success)
    {
        char infoLog[512];
        glGetProgramInfoLog(shaderProgram, sizeof(infoLog), NULL, infoLog);
        cout << "ERROR link shader program failed" << endl << infoLog << endl;
    }
    else
    {
        // 链接成功，着色器已经没用了，可以删除
        glDeleteShader(vertexShader);
        glDeleteShader(fragmentShader);
    }

    cout << "compile shader success" <<endl;

    return shaderProgram;
};

int ShaderProgram::compileShader(const char* shaderSource, int shaderType)
{
    // 1、创建着色器对象，并分配id，参数 GL_VERTEX_SHADER
    // 代表创建一个顶点着色器

    unsigned int vertexShader;
    vertexShader = glCreateShader(shaderType);

    // 2、把顶点着色器源代码附加到 着色器对象中
    glShaderSource(vertexShader, 1, &shaderSource, NULL);

    // 3、编译顶点着色器
    glCompileShader(vertexShader);

    // 4、检查编译是否成功
    int success;
    glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);

    if (!success)
    {
        char infoLog[512];
        glGetShaderInfoLog(vertexShader, sizeof(infoLog), NULL, infoLog);
        auto shaderName = GL_FRAGMENT_SHADER == shaderType?"fragment" :"vertex";
        cout << "ERROR: compile "<< shaderName <<" shader failed" << endl
             << infoLog << endl;
    }

    return vertexShader;
}